package com.bangcommunity.bbframe.fdfs.connection;

import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

import com.bangcommunity.bbframe.fdfs.StorageAddress;
import com.bangcommunity.bbframe.fdfs.config.FdfsClientConfig;

import java.io.IOException;

/**
 * @author tanghc
 * @date 18/6/22
 */
public class StorageConnectionFactory implements KeyedPooledObjectFactory<StorageAddress, StorageConnection> {

    private FdfsClientConfig fastdfsClientConfig;

    public StorageConnectionFactory(){
        this(null);
    }
    public StorageConnectionFactory(FdfsClientConfig fastdfsClientConfig){
        super();
        this.fastdfsClientConfig = fastdfsClientConfig;
    }

    @Override
    public PooledObject<StorageConnection> makeObject(StorageAddress key) throws Exception {
        StorageConnection storageConnection = new StorageConnectionImpl(key);
        return new DefaultPooledObject<>(storageConnection);
    }

    @Override
    public void destroyObject(StorageAddress key, PooledObject<StorageConnection> p) throws Exception {
        StorageConnection storageConnection = p.getObject();
        storageConnection.close();
    }

    @Override
    public boolean validateObject(StorageAddress key, PooledObject<StorageConnection> p) {
        StorageConnection storageConnection = p.getObject();
        try {
            return !storageConnection.isClosed();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void activateObject(StorageAddress key, PooledObject<StorageConnection> p) throws Exception {

    }

    @Override
    public void passivateObject(StorageAddress key, PooledObject<StorageConnection> p) throws Exception {

    }
    public GenericKeyedObjectPoolConfig getClientPoolConfig(){
        return fastdfsClientConfig.getStorageClientPoolConfig();
    }

    public FdfsClientConfig getFastdfsClientConfig() {
        return fastdfsClientConfig;
    }

    public void setFastdfsClientConfig(FdfsClientConfig fastdfsClientConfig) {
        this.fastdfsClientConfig = fastdfsClientConfig;
    }
}
